from setting import backtest
from setting import data
import polars as pl
import pickle
from setting.crate import *

# 策略名称 - 用于生成测试报告
strategy_name = "data_test"

# 合约池
base_data_symbol = ["CFFEX_IF00_300"]  # 基准合约列表(用于时间轴)
trade_data_symbol = ["CFFEX_IF00_300", "CFFEX_IC00_300", "CFFEX_IH00_300"]  # 待交易合约
extra_data_symbol = ["CFFEX_IF00_86400", "CFFEX_IC00_86400", "CFFEX_IH00_86400"]  # 跨周期调用数据

# 加载数据
base_data, all_trade_data = data.get_data(
    base_data_symbol,
    trade_data_symbol + extra_data_symbol,
    "20251001",
    "20251015"
)

# 分割数据
trade_data = {k: v for k, v in all_trade_data.items() if k in trade_data_symbol}
extra_data = {k: v for k, v in all_trade_data.items() if k in extra_data_symbol}

# 回测参数配置
initial_cash = 1000 * 10000.0  # 初始资金:1000万
fee_rate = 3.0 / 10000  # 手续费率:万分之三

# 加载合约参数
with open("setting/volume_multiple.pkl", "rb") as f:
    loaded_volume = pickle.load(f)
with open("setting/margin_ratio.pkl", "rb") as f:
    loaded_margin = pickle.load(f)

deposit_rates = loaded_margin
multipliers = loaded_volume


class Strategy(PythonStrategy):
    """
    主要用于查看数据获取的结果
    """

    def __init__(self, backtest_instance, trade_data, extra_data):
        super().__init__(backtest_instance, trade_data, extra_data)
        print("🔍 调试策略初始化完成")

    def on_bar(self, timestamp):
        """K线回调函数 - 每个时间戳调用一次,用于调试数据获取"""
        for symbol in self.trade_data.keys():
            recent_data = self.get_recent_data(symbol, timestamp, lookback=1, require_exact_match=True)
            if recent_data is not None:
                self.debug_data_output(extract_symbol_base(symbol), recent_data, timestamp)

    def debug_data_output(self, symbol, recent_data, timestamp):
        """
        调试数据输出函数 - 查看获取的数据结果
        
        Args:
            symbol: 品种代码
            recent_data: 最近的数据切片
            timestamp: 当前时间戳
        """
        print(f"\n📊 品种: {symbol}")
        print(f"📅 当前日期: {self.backtest_instance.today}")
        print(f"⏰ 时间戳: {timestamp}")
        
        # 输出分钟数据信息
        print("📈 分钟数据:")
        print(f"  数据形状: {recent_data.shape}")
        if len(recent_data) > 0:
            print(f"  最新收盘价: {recent_data['close'][-1]}")
            print(f"  最新时间: {recent_data['datetime'][-1]}")
        
        # 获取并输出日线数据信息
        recent_data_daily = self.get_recent_data(symbol + "_86400", timestamp, lookback=2, require_exact_match=False)
        print("📅 日线数据:")
        if recent_data_daily is not None:
            print(f"  数据形状: {recent_data_daily.shape}")
            if len(recent_data_daily) > 0:
                print(f"  最新收盘价: {recent_data_daily['close'][-1]}")
                print(f"  最新时间: {recent_data_daily['datetime'][-1]}")
        else:
            print("  日线数据为空")
        
        print("=" * 50)


def main():
    """
    主函数 - 配置并运行回测调试
    """
    # 初始化回测引擎
    my_backtest = backtest.BackTest(initial_cash, fee_rate, deposit_rates, multipliers, trade_data)

    # 创建策略实例 - 使用子类Strategy
    strategy = Strategy(my_backtest, trade_data, extra_data)

    # 准备回测时间序列
    datetime_strings = base_data.get_column("datetime").dt.strftime("%Y-%m-%d %H:%M:%S")

    # 启动回测调试
    print("🚀 开始回测调试...")
    backtest.start_backtest(
        strategy, 
        my_backtest, 
        datetime_strings, 
        base_data.get_column("timestamps"), 
        strategy_name
    )

if __name__ == "__main__":
    main()